import { defineStore } from 'pinia'

export interface AmapKeys {
    amapKey: string
    amapSafeCode: string
    amapWebServiceKey: string
    amapAndroidKey: string
    amapIosKey: string
}

export const useAmapKeyStore = defineStore('useAmapKeyStore', {
    state: (): AmapKeys => {
        return {
            amapKey: '', // 高德 JSAPI key
            amapSafeCode: '', // 高德 JSAPI 安全密钥
            amapWebServiceKey: '', // 高德 Web服务 key
            amapAndroidKey: '', // 高德 Android key
            amapIosKey: '', // 高德 iOS key
        }
    },
    actions: {
        // 设置全部 key
        SET_ALL_KEY({ amapKey, amapSafeCode, amapWebServiceKey, amapAndroidKey, amapIosKey }: AmapKeys) {
            this.SET_AMAP_KEY(amapKey)
            this.SET_AMAP_SAFE_CODE(amapSafeCode)
            this.SET_AMAP_WEB_SERVICE_KEY(amapWebServiceKey)
            this.SET_AMAP_ANDROID_KEY(amapAndroidKey)
            this.SET_AMAP_IOS_KEY(amapIosKey)
        },
        // 设置高德 JSAPI key
        SET_AMAP_KEY(key: string) {
            if (key) {
                this.amapKey = key || import.meta.env.VITE_GD_MAP_KEY
            }
        },
        // 设置高德 JSAPI 安全密钥
        SET_AMAP_SAFE_CODE(key: string) {
            if (key) {
                this.amapSafeCode = key || import.meta.env.VITE_GD_MAP_SAFECODE
                // @ts-ignore-next-line
                window._AMapSecurityConfig = {
                    securityJsCode: key || import.meta.env.VITE_GD_MAP_SAFECODE,
                }
            }
        },
        // 设置高德 Web服务 key
        SET_AMAP_WEB_SERVICE_KEY(key: string) {
            if (key) {
                this.amapWebServiceKey = key || import.meta.env.VITE_GD_WEB_MAP_KEY
            }
        },
        // 设置高德 Android key
        SET_AMAP_ANDROID_KEY(key: string) {
            if (key) {
                this.amapAndroidKey = key || import.meta.env.VITE_GD_ANDROID_MAP
            }
        },
        // 设置高德 iOS key
        SET_AMAP_IOS_KEY(key: string) {
            if (key) {
                this.amapIosKey = key || import.meta.env.VITE_GD_IOS_MAP
            }
        },
    },
    getters: {
        getAmapKey(state) {
            return state.amapKey
        },
        getAmapSafeCode(state) {
            return state.amapSafeCode
        },
        getAmapWebServiceKey(state) {
            return state.amapWebServiceKey
        },
        getAmapAndroidKey(state) {
            return state.amapAndroidKey
        },
        getAmapIosKey(state) {
            return state.amapIosKey
        },
    },
})
